
library(matchMulti)
library(dplyr)
library(xtable)

rm(list=ls())

'%!in%' <- function(x,y)!('%in%'(x,y))

data(catholic_schools)
catholic_schools <- catholic_schools %>% filter(female_mean>.30, female_mean<.75)

catholic_schools$sectorf <- factor(catholic_schools$sector, label=c("Public", "Catholic"))

#Number of Treated Schools
length(table(catholic_schools$school[catholic_schools$sector==1]))

t.s.id <- unique(catholic_schools$school[catholic_schools$sector==1])
c.s.id <- unique(catholic_schools$school[catholic_schools$sector==0])


setwd("~/Dropbox/Group Matches/Analysis/Catholic/ReplicationFiles/R output")
load("cschools_matchout.RData")


match.data4 <- as.data.frame(match_4$matched)
length(unique(match.data4$school[match.data4$sector==1]))

match.data5 <- as.data.frame(match_5$matched)
length(unique(match.data5$school[match.data5$sector==1]))
t.m.s.id <- unique(match.data5$school[match.data5$sector==1])
t.um.s.id <- t.s.id[t.s.id %!in% t.m.s.id]
new.s.id <- c(t.um.s.id, c.s.id)


## Data for Profiling
new.data <- catholic_schools[catholic_schools$school %in% new.s.id,] 


# Calc Balance
all.cov <- c('minority','female','ses','minority_mean', 'female_mean', 'size', 'acad', 'discrm', 'ses_mean')

# Balance Before Matching
bal.unmatch <- balanceTable(catholic_schools[c(all.cov,'sector')],  treatment = 'sector')

# Balance After Matching 20 Schools
bal.match.20 <- balanceTable(match.data4[c(all.cov,'sector')],  treatment = 'sector')

# Balance After Matching 10 Schools
bal.match.10 <- balanceTable(match.data5[c(all.cov,'sector')],  treatment = 'sector')

# Balance After Trimming 
bal.profile <- balanceTable(new.data[c(all.cov,'sector')],  treatment = 'sector')

# Make Table
profile.tab <- cbind(bal.unmatch[,2], bal.match.10[,2], bal.match.10[,1], bal.profile[,1])
rownames(profile.tab) <- c("Minority Student", "Female", "Student SES", "% Students Minority", "% Students Female",
			"Enrollment", "% Students on Academic Track", "Disciplinary Climate Scale", "School SES Average")


xtable(profile.tab[6:9,])
